package com.neusoft.bizcore.auth.repository.impl;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.auth.model.AuthRole;
import com.neusoft.bizcore.auth.model.QAuthRole;
import com.neusoft.bizcore.auth.repository.CustomizedAuthRoleRepository;
import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedAuthRoleRepositoryImpl extends AbstractRepository
        implements CustomizedAuthRoleRepository {

    @Override
    public List<AuthRole> search(Searchable searchable) {
        final QAuthRole qAuthRole = QAuthRole.authRole;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<AuthRole> query = this.query().selectFrom(qAuthRole);
        query.where(where);

        return query.fetch();
    }

    @Override
    public Page<AuthRole> search(final Pageable pageable, final Searchable searchable) {
        final QAuthRole qAuthRole = QAuthRole.authRole;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<AuthRole> query = this.query().selectFrom(qAuthRole);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return AuthRole.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QAuthRole qAuthRole = QAuthRole.authRole;

        where.and(super.containsStr(qAuthRole.code, searchable, "code"));
        where.and(super.containsStr(qAuthRole.name, searchable, "name"));
        if (searchable.hasKey("roleCodeArray")) {
            where.and(super.inStrings(qAuthRole.code, searchable, "roleCodeArray"));
        }
        return where;
    }

}
